package com.fintech.pangu.rocketmq.metrics;

import com.alibaba.rocketmq.client.hook.SendMessageContext;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.util.StringUtils;

/**
 * RocketMQMetricsCollector收集指标数据时的入参
 * 封装记录指标数据时的必要数据，生成Tags
 */
@Data
@Builder
@AllArgsConstructor
public class RocketMQSendMessageContext {

    /** 是否生产成功 */
    private boolean success;

    /** 通讯类型 */
    private String communicationMode;

    /** 主题 */
    private String topic;

    /** 生产组 */
    private String producerGroup;

    /** 发送状态 */
    private String sendStatus;

    /** 异常 */
    private Exception exception;

    /** 异常响应编码，默认值-1 */
    private Integer responseCode = -1;

    /** 耗时 (ms) */
    private long duration = 0L;


    /**
     * 根据RocketMQ SendMessageContext发送消息上下文构造
     * 在SendMessageMetricHookImpl使用
     * @param sendMessageContext
     */
    public RocketMQSendMessageContext(SendMessageContext sendMessageContext){
        if(sendMessageContext.getCommunicationMode()!=null){
            this.communicationMode = sendMessageContext.getCommunicationMode().name();
        }
        if(sendMessageContext.getMessage()!=null && StringUtils.hasText(sendMessageContext.getMessage().getTopic())){
            this.topic = sendMessageContext.getMessage().getTopic();
        }
        if(StringUtils.hasText(sendMessageContext.getProducerGroup())){
            this.producerGroup = sendMessageContext.getProducerGroup();
        }
        if(sendMessageContext.getSendResult()!=null && sendMessageContext.getSendResult().getSendStatus()!=null){
            this.sendStatus = sendMessageContext.getSendResult().getSendStatus().name();
        }
        if(sendMessageContext.getException()!=null){
            this.exception = sendMessageContext.getException();
            this.success = false;
        }
        else {
            this.success = true;
        }
    }

}
